import os
from datetime import datetime

import requests
import pandas as pd

def fetch_region_transactions(api_url, output_file="region_transaction_data.xlsx"):
    """
    从API获取地区交易额数据，转换为亿为单位并导出到Excel
    
    参数:
        api_url: API接口地址
        output_file: 输出Excel文件名
    """
    try:
        # 调用API获取数据
        print(f"正在请求API: {api_url}")
        response = requests.get(api_url)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()
        
        if not data:
            print("API返回数据为空")
            return
        
        # 转换交易额单位（从元到亿）
        print("正在转换交易额单位...")
        for item in data:
            # 遍历所有包含"交易额"的字段进行单位转换
            for key in list(item.keys()):
                if "交易额" in key and isinstance(item[key], (int, float)):
                    # 保留两位小数，转换为亿
                    item[key] = round(item[key] / 10**8, 2)

        # 创建DataFrame并保存为Excel
        dateStamp = datetime.now().strftime("%Y%m%d")
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_dir = f"../spiltExcel/input/{dateStamp}"
        os.makedirs(output_dir, exist_ok=True)

        output_file = f"{output_dir}/jye_{timestamp}.xlsx"
        df = pd.DataFrame(data)
        df.to_excel(output_file, index=False)
        print(f"数据已成功导出到: {output_file}")
        
    except requests.exceptions.RequestException as e:
        print(f"API请求失败: {str(e)}")
    except Exception as e:
        print(f"数据处理错误: {str(e)}")

def process():
    # API地址
    api_url = "http://127.0.0.1:6666/api/public/stock_szse_area_summary"

    # 执行转换
    fetch_region_transactions(api_url)

if __name__ == "__main__":
    # API地址
    api_url = "http://127.0.0.1:6666/api/public/stock_szse_area_summary"
    
    # 执行转换
    fetch_region_transactions(api_url)
